<route lang="json5" type="page">
{
  layout: 'default',
  style: {
    navigationBarTitleText: '快速购币',
  },
}
</route>

<template>
  <view style="height: 100vh; padding: 30rpx; background-color: white">
    <wd-text text="快速购币" bold></wd-text>
    <uni-link href="https://uniapp.dcloud.io/" text="https://uniapp.dcloud.io/"></uni-link>
    <wd-gap bg-color="#FFFFFF"></wd-gap>
    <wd-radio-group v-model="value" cell max-width="300px">
      <wd-radio :value="item.id" shape="button" v-for="item in packageList as any[]" :key="item.id">
        {{ item.packagePrice / 100 }}元 = {{ item.gameCount }}游戏币
      </wd-radio>

      <wd-radio value="custom" shape="button">自定义</wd-radio>
    </wd-radio-group>

    <wd-cell title="填写购买的币数" vertical v-if="value === 'custom'">
      <wd-input-number v-model="num" @blur="blur" @focus="focus" />
    </wd-cell>

    <view class="mt-3">
      <wd-button type="primary" :disabled="isfocus" block @click="buyGameCoin">确认购买</wd-button>
    </view>

    <!-- <navigator url="https://qr.alipay.com/bax05989ga3zszxnk2bn305f" hover-class="navigator-hover">
					<button type="default">跳转到新页面</button>
				</navigator>
    <uni-link href="https://qr.alipay.com/bax05989ga3zszxnk2bn305f" text="https://uniapp.dcloud.io/"></uni-link> -->
    <!-- <web-view :src="'https://qr.alipay.com/bax05989ga3zszxnk2bn305f'"></web-view> -->
  </view>
</template>

<script lang="ts" setup>
import { onLoad, onShow } from '@dcloudio/uni-app'
import { httpPost } from '@/utils/http'

const deviceNo = ref('')
// 获取列表
const { data: packageList } = useRequest(
  async () => await httpPost('/api/app/order/package/list'),
  {
    immediate: true,
  },
)

const value = ref<number | string>(1)

const num = ref(1)

const systemInfo = ref()

const isfocus = ref(false)

const blur = () => {
  console.log('qwer')
  isfocus.value = false

  // num.value = Number(value.value)
}

const focus = () => {
  console.log('focus')
  isfocus.value = true
}

onLoad((_options) => {
  console.log('_options', _options)

  // const q = decodeURIComponent(_options.q) // 获取到二维码原始链接内容
  // const scancode_time = parseInt(_options.scancode_time) // 获取用户扫码时间 UNIX 时间戳

  // if (q) {

  // }
  if (_options.q) {
    const q = decodeURIComponent(_options.q)

    const [, deviceStr] = q?.split('deviceNo=')

    const parts = deviceStr.split(/(?<=\d)(?=[A-Za-z])|(?<=[A-Za-z])(?=\d)/)

    deviceNo.value = deviceStr
  } else {
    deviceNo.value = _options.deviceNo
  }
  systemInfo.value = uni.getSystemInfoSync()
})

// 一进页面，如果没登陆，自动进行登陆
onShow(() => {
  let _code = ''

  // 判断缓存是否有openId
  if (uni.getStorageSync('APP_OPEN_ID')) {
    return
  }

  wx.login({
    success: (res) => {
      console.log('res,', res)

      _code = res.code

      wx.getUserInfo({
        success: async function (res) {
          console.log(res.encryptedData) // 这是加密数据
          console.log(res.iv) // 解密算法的初始向量

          // 调用后端接口，进行登陆
          const _result = await httpPost('/api/app/user/login/mini', {
            code: _code,
            encryptedData: res.encryptedData,
            iv: res.iv,
          })

          console.log('_result_result_result_result', _result)

          // 本地缓存起来
          uni.setStorageSync('APP_OPEN_ID', (_result as any)?.openid)

          console.log('_result', _result)
        },
      })
    },
  })
})

const buyGameCoin = async () => {
  uni.showLoading({
    title: '正在购买...',
    mask: true,
  })

  // 当前选择的是套餐还是自定义
  const isCustom = value.value === 'custom'

  uni.login({
    provider: 'weixin',
    success: async (res) => {
      console.log('loginloginloginlogin', res)
    },
  })

  let _params: any = {}

  if (isCustom) {
    _params.payAmount = num.value * 100
  } else {
    _params.packageId = value.value
  }

  const systemInfo = uni.getSystemInfoSync()

  try {
    const res = await httpPost('/api/app/order/order/buy', {
      // 设备号
      deviceNo: deviceNo.value,
      payType: systemInfo.hostName === 'WeChat' ? 1 : 2,
      openId: uni.getStorageSync('APP_OPEN_ID'),

      // openId: "ohXCz7eo7NTIVtPlXDX19yA54rJM",
      // openId: systemInfo.hostName === "WeChat" ?  uni : systemInfo.userId,
      ..._params,
    })

    // uni.showToast({ title: systemInfo.hostName })

    // console.log('res?.resp_data?.acc_resp_fields', res?.resp_data?.acc_resp_fields);

    // window.open(res?.resp_data?.acc_resp_fields?.code)

    if (systemInfo.hostName === 'WeChat') {
      wx.requestPayment({
        timeStamp: res?.resp_data?.acc_resp_fields?.time_stamp,
        nonceStr: res?.resp_data?.acc_resp_fields?.nonce_str,
        package: res?.resp_data?.acc_resp_fields?.package,
        signType: res?.resp_data?.acc_resp_fields?.sign_type,
        paySign: res?.resp_data?.acc_resp_fields?.pay_sign,
        success(res) {
          uni.showToast({
            title: '支付成功',
            icon: 'success',
          })
        },
        fail(res) {
          uni.showToast({
            title: '支付失败',
            icon: 'error',
          })
        },
      })
    } else {
      // console.log('resresres',res);

      if (!res?.resp_data?.acc_resp_fields?.code) {
        return uni.showToast({
          title: '支付失败，请联系管理员',
          icon: 'error',
        })
      }

      const link = document.createElement('a')
      link.href = res?.resp_data?.acc_resp_fields?.code
      link.target = '_blank'
      link.rel = 'noopener noreferrer'
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)

      // window.open(res?.resp_data?.acc_resp_fields?.code)
      // uni.requestPayment({
      //   provider: "alipay",
      //   orderInfo: res?.req_data,
      //   success(result) {
      //     console.log('支付成功');

      //   },
      //   fail(result) {
      //     console.log('支付失败', result);
      //   },
      // })
    }

    console.log('resresres', res)

    // wx.showToast({ title: '购买成功' })
  } catch (error) {
    console.log('error', error)
    // uni.hideLoading()
  }
}
</script>

<style lang="scss" scoped>
:deep(.wd-radio) {
  width: 50% !important;
}
</style>
